package com.xl.rentkeeper.act.kanfang;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.xl.fuse.protos.viewroom.RoomInfo;
import com.xl.fuse.protos.viewroom.RoomStatus;
import com.xl.fuse.protos.viewroom.SignInfo;
import com.xl.rentkeeper.App;
import com.xl.rentkeeper.R;
import com.xl.rentkeeper.act.BaseAct;
import com.xl.rentkeeper.act.SearchRoomInfoAct;
import com.xl.rentkeeper.business.OrderLogic;
import com.xl.rentkeeper.business.UserLogic;
import com.xl.rentkeeper.entity.Order;
import com.xl.rentkeeper.util.DialogUtil;
import com.xl.rentkeeper.util.TimeUtils;
import com.xl.rentkeeper.util.TipMapping;
import com.xl.rentkeeper.util.Util;
import com.xl.rentkeeper.view.TimePopupWindow;
import com.xl.rentkeeper.view.TitleBar;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2015/8/17.
 */
public class AffirmOrderRoomAct extends BaseAct implements View.OnClickListener {
    private TimePopupWindow pwTime;
    private EditText mETCoupon;
    private EditText mETUserName;
    private EditText mETPhone;
    private EditText mETIDNumber;
    private TextView mTVRoomName;
    private TextView mTVRoominfoStatus1;
    private TextView mTVRoominfoPrice1;
    private TextView mTVBeginTime;
    private TextView mTVEndTime;
    private EditText mETLiveNumber;
    private EditText mETPrice;
    private EditText mETYajin;
    private EditText mETAmount;
    private EditText mETRemark;

    private long mTime = 0;
    private long mBeginTime = 0;
    private long mEndTime = 0;

    private Date mBeginDate = new Date();
    private Date mEndDate = new Date();

    private Order mOrder;
    private Dialog mDialog;
    private RoomInfo roomInfo = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_affirm_room);

        TitleBar tb = (TitleBar) findViewById(R.id.tb);
        setTranslucentStatus();
        initTitleBar(tb);
        initView();
        initData();
    }


    private void initView() {
        // mETCoupon = (EditText) findViewById(R.id.et_coupon);
        mETUserName = (EditText) findViewById(R.id.et_userName);
        mETPhone = (EditText) findViewById(R.id.et_phone);
        mTVRoominfoStatus1 = (TextView) findViewById(R.id.tv_roominfo_status1);
        mTVRoominfoPrice1 = (TextView) findViewById(R.id.tv_price1);
        mETIDNumber = (EditText) findViewById(R.id.et_IDNumber);
        mTVRoomName = (TextView) findViewById(R.id.tv_roomName);
        mTVBeginTime = (TextView) findViewById(R.id.tv_beginTime);
        mTVEndTime = (TextView) findViewById(R.id.tv_endTime);
        mETLiveNumber = (EditText) findViewById(R.id.et_liveNumber);
        mETPrice = (EditText) findViewById(R.id.et_price);
        mETYajin = (EditText) findViewById(R.id.et_yajin);
        mETAmount  = (EditText) findViewById(R.id.et_amount );
        mETRemark = (EditText) findViewById(R.id.et_remark);

        mTVRoomName.setOnClickListener(this);
        mTVBeginTime.setOnClickListener(this);
        mTVEndTime.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = this.getIntent();
        mOrder = (Order) intent.getSerializableExtra("msg");

        if (mOrder != null) {
            mETUserName.setText(mOrder.viewOrder.name);
            mETPhone.setText(mOrder.viewOrder.phone);

           // mTVLease.setText(mOrder.viewOrder.signInfo);
           /* if (mOrder.viewOrder.signRoom != null){
                mTVLease.setText(Util.replaceTimeNull(mOrder.viewOrder.signRoom.contractEndTime));
            }*/

            if (mOrder.viewOrder.viewRooms != null && mOrder.viewOrder.viewRooms.size() > 0) {
                roomInfo = mOrder.viewOrder.viewRooms.get(0);
                if(roomInfo!=null){
                    if(roomInfo.name!=null){
                        mTVRoomName.setText(roomInfo.name);
                        if (roomInfo.price != null && roomInfo.price != 0) {
                            mETPrice.setText(String.valueOf((int)(double)roomInfo.price));
                        }
                    }
                    Util.setRoomStatus(mTVRoominfoStatus1, roomInfo, "affirm_order");
                    Util.setRoomPrice(mTVRoominfoPrice1,roomInfo,"affirm_order");
                }
            }
        }

    }

    public void submit(View v) {

        final String mUserName = mETUserName.getText().toString().trim();
        final String mPhone = mETPhone.getText().toString().trim();
        final String mIDNumber = mETIDNumber.getText().toString().trim();
        final String yajin = mETYajin.getText().toString().trim();
        final String amount = mETAmount.getText().toString().trim();
        final String remark = mETRemark.getText().toString().trim();

        if (!Util.isNumber(mETLiveNumber.getText().toString().trim())) {
            App.showToast("人数只能填写数字");
            return;
        }
        if (!Util.isNumber(mETPrice.getText().toString().trim())) {
            App.showToast("金额只能填写数字");
            return;
        }

        int mLiveNumber = 0;
        double mPrice = 0;
        if (TextUtils.isEmpty(mETLiveNumber.getText().toString().trim())) {
            App.showToast(R.string.fill_in_liveNumber);
            return;
        } else {
            mLiveNumber = Integer.parseInt(mETLiveNumber.getText().toString().trim());
        }

        if (TextUtils.isEmpty(mETPrice.getText().toString().trim())) {
            App.showToast(R.string.fill_in_month_price);
            return;
        } else {
            mPrice = Double.parseDouble(mETPrice.getText().toString().trim());
        }


        if (roomInfo == null) {
            App.showToast(R.string.fill_in_roomName);
            return;
        } else if (mBeginTime == 0) {
            App.showToast(R.string.fill_in_begintime);
            return;
        } else if (mEndTime == 0) {
            App.showToast(R.string.fill_in_endtime);
            return;
        } else if ("".equals(mUserName)) {
            App.showToast(R.string.fill_in_userName);
            return;
        } else if ("".equals(mPhone)) {
            App.showToast(R.string.fill_in_phone);
            return;
        } else if ("".equals(mIDNumber)) {
            App.showToast(R.string.fill_in_IDNumber);
            return;
        } else if (0 >= mLiveNumber || mLiveNumber > 8) {
            App.showToast(R.string.fill_in_liveNumber_err);
            return;
        } else if (0 >= mPrice) {
            App.showToast(R.string.fill_in_month_price);
            return;
        }
        double tmpyajin =0;
        try{
            tmpyajin = Double.parseDouble(yajin);
        }catch (Exception e){

        }
        double tmpamount =0;
        try{
            tmpamount = Double.parseDouble(amount);
        }catch (Exception e){

        }
        final double yajin_ = tmpyajin;
        final double amount_ = tmpamount;
        String msg = "请确认所填信息完整无误,确认后该房源将下架";
        final int finalMLiveNumber = mLiveNumber;
        final double finalMPrice = mPrice;
        DialogUtil.showMsgInfoDialog(this, new DialogUtil.DismissClickListener() {
            @Override
            public void okClick() {
                SignInfo signInfo = new SignInfo.Builder().roomId(roomInfo.roomId).couponCode(null).name(mUserName).phone(mPhone).personNum(finalMLiveNumber).contractStartTime(mBeginTime)
                        .contractEndTime(mEndTime).IdNumber(mIDNumber).finalPrice(finalMPrice).signStewardId(UserLogic.getInstance().getUid()).hasAmount(amount_).hasAmountRemark(remark).deposit(yajin_).build();
                if (mOrder == null) {
                    mDialog = DialogUtil.showProgressDialog(AffirmOrderRoomAct.this, R.string.loading);
                    OrderLogic.getInstance().addReserveRoom(signInfo);
                } else {
                    mDialog = DialogUtil.showProgressDialog(AffirmOrderRoomAct.this, R.string.loading);
                    OrderLogic.getInstance().reserveRoom(mOrder.id, true, signInfo, null);
                }
            }

            @Override
            public void cancelClick() {

            }
        }, msg, "确认订房", null, null);


    }


    public String[] monitorEvents() {
        return new String[]{PMS_LOGIC_ReserveRoom, PMS_LOGIC_AddReserveRoom};
    }

    @Override
    public void onEvent(String event, boolean ret,String errInfo, Object[] data) {
        super.onEvent(event, ret,errInfo, data);
        if (event.equals(OrderLogic.PMS_LOGIC_ReserveRoom)) {
            if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
            if (ret) {
                setResult(110);
                finish();
            } else {
                App.showToast(errInfo);
            }
        } else if (event.equals(OrderLogic.PMS_LOGIC_AddReserveRoom)) {
            if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
            if (ret) {
                setResult(110);
                finish();
//                overridePendingTransition(R.anim.base_slide_remain, R.anim.base_slide_right_out);
            } else {
                App.showToast(errInfo);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_roomName:
                Intent intent = new Intent(this, SearchRoomInfoAct.class);
                intent.putExtra("position", 0);
                startActivityForResult(intent, 1);
                break;
            case R.id.tv_beginTime:
                setBeginTime();
                closeKeyboard(mETLiveNumber);
                closeKeyboard(mETPrice);
                pwTime.showAtLocation(mTVBeginTime, Gravity.BOTTOM, 0, 0,mBeginDate);
                break;

            case R.id.tv_endTime:
               setEndTime();
                closeKeyboard(mETLiveNumber);
                closeKeyboard(mETPrice);
                pwTime.showAtLocation(mTVEndTime, Gravity.BOTTOM, 0, 0, mEndDate);
                break;
        }

    }

    private void setBeginTime() {
        //时间选择器
        pwTime = new TimePopupWindow(this, TimePopupWindow.Type.YEAR_MONTH_DAY);
        //时间选择后回调
        pwTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                mTVBeginTime.setText(getTime(date));
                mBeginDate = date;
                mBeginTime = date.getTime();
            }
        });
    }

    private void setEndTime() {
        //时间选择器
        pwTime = new TimePopupWindow(this, TimePopupWindow.Type.YEAR_MONTH_DAY);
        //时间选择后回调
        pwTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                mTVEndTime.setText(getTime(date));
                mEndDate = date;
                mEndTime = date.getTime();
            }
        });
    }

    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 || resultCode == 1) {
            if (data != null) {
                RoomInfo room = (RoomInfo) data.getSerializableExtra("info");
                int position = data.getIntExtra("position", 0);
                roomInfo = room;
                refreshView(position);
            }
        }
    }

    private void refreshView(int position) {
        mTVRoomName.setText(roomInfo.name);
        if (roomInfo.price != null ){
            double price = roomInfo.price;
            mETPrice.setText(""+(int)price);
        }
        Util.setRoomStatus(mTVRoominfoStatus1, roomInfo, "affirm_order");
        Util.setRoomPrice(mTVRoominfoPrice1,roomInfo,"affirm_order");
    }
}
